import tkinter as tk
from tkinter import PhotoImage
import getYoutube
import to_mp3
import threading
import time
import setting
import sys
import os
import requests
download_thread_running = False

class WIN():
    def __init__(self):
        self.ytb = getYoutube.YTB()
        self.downloading_win = None
        # 创建主窗口
        self.root = tk.Tk()
        self.root.title("ToMP3")
        # 设置窗口图标
        self.root.iconbitmap(r"D:/WorkStation/项目集/youtube下载音视频/record.ico")
        # 设置任务栏显示的图标
        # self.root.iconphoto(True, tk.PhotoImage(file="record.ico"))
        # self.root.iconphoto(True, tk.PhotoImage(file="D:/WorkStation/项目集/youtube下载音视频/record.ico"))

        # 设置窗口大小和位置
        window_width = 782
        window_height = 631
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        x = (screen_width / 2) - (window_width / 2)
        y = (screen_height / 2) - (window_height / 2)
        self.root.geometry(f"{window_width}x{window_height}+{int(x)}+{int(y)}")


        # 禁止用户调整窗口大小
        self.root.resizable(width=False, height=False)
        # 添加背景图
        bg_image = PhotoImage(file=r"D:\\sa.png")  # 替换为你的背景图路径
        background_label = tk.Label(self.root, image=bg_image)
        background_label.place(relx=0.5, rely=0.5, anchor="center")

        # 添加其他窗口部件

        label = tk.Label(self.root, text="Youtube To MP3", font=("微软雅黑", 24), bg='#BCA7A6')
        label.place(relx=0.5, rely=0.5, anchor="center", y=-100)  # 向下移动 200 个像素
        # label.config(bg=None)

        # 添加文本框
        self.url_entry = tk.Entry(self.root, font=("微软雅黑", 16), width=50)  # 设置文本框宽度为 30 个字符
        self.url_entry.place(relx=0.5, rely=0.5, anchor="center", y=-50)  # 向下移动 150 个像素

        # 添加按钮
        download_button = tk.Button(self.root, text="下载MP3", height=1, command=self.download_mp3, bg="#FBA79C")
        download_button.place(relx=0.5, rely=0.5, anchor="center", y=-10)  # 向下移动 100 个像素
        self.root.mainloop()

    def center_window(self,window):
        window.update_idletasks()
        window_width = window.winfo_width()
        window_height = window.winfo_height()
        screen_width = window.winfo_screenwidth()
        screen_height = window.winfo_screenheight()
        x = (screen_width - window_width) // 2
        y = (screen_height - window_height) // 2
        window.geometry(f"{window_width}x{window_height}+{x}+{y}")

    def modal(self,t):
        m_window = tk.Toplevel(self.root)
        m_window.title("提示")
        m_window.geometry("300x100")
        m_window.resizable(width=False, height=False)
        m_window.grab_set()  # 设置模态窗口
        self.center_window(m_window)  # 将模态窗口放置在主窗口中间
        prompt_label = tk.Label(m_window, text=t)
        prompt_label.pack(pady=10)
        ok_button = tk.Button(m_window, text="OK", command=m_window.destroy)
        ok_button.pack(pady=10)
        return m_window
    
    def download_mp3(self):
        try:
            self.downloading_win =  self.modal("正在努力下载中，请稍等......")

            # ytb = getYoutube.YTB()
            url = self.url_entry.get()
            # 在这里添加下载 MP3 的代码
            print("Downloading MP3 from:", url)
            global download_thread_running
            if not download_thread_running:
                download_thread_running = True
                self.t2 = threading.Thread(target=self.ytb.youtube_a,args=(self,))
                self.t2.start()
            # t2.join()
            while self.t2.is_alive():
                self.root.update()  # 更新界面，确保界面响应
                time.sleep(0.1)  # 等待一小段时间再检查线程状态
            time.sleep(1)
            input_file = self.ytb.file_path
            print(input_file)
            output_file = input_file.replace('Webm','mp3')
            print(output_file)
            to_mp3.webm_to_mp3(input_file, output_file) 

            # 下载完成后调用 download_complete 函数
            self.download_complete()   
            download_thread_running = False
        except:
            self.downloading_win.destroy
    
    # 在下载完成后更新提示信息并添加 OK 按钮
    def download_complete(self):
        self.downloading_win.destroy
        self.completed_win = self.modal(r"下载完成！请在audio目录下查看")

    # if __name__ == '__main__':
    #     # 运行窗口主循环
    #     self.root.mainloop()
    